import com.westos.controller.Controller;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: 大强
 * @CreateTime: 2020/1/12
 * @Company: 西部开源教育科技有限公司
 */

@WebServlet(value = "/mvc")
public class MVCServlet extends HttpServlet {

    private Map<String,Object> cache;

    @Override
    public void init() throws ServletException {
        super.init();
        cache=new HashMap<String, Object>();
    }

    private Controller findControllerByname(String name) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        if(cache.containsKey(name)){
            return (Controller)cache.get(name);
        }else{
            String sname="";
            sname=Controller.class.getPackage().getName();
            sname=sname+"."+name;
            Class<?> aClass = Class.forName(sname);
            Object o = aClass.newInstance();
            cache.put(name,o);
            return (Controller)o;
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String sname = req.getParameter("sname");
            //增加缓存功能
            Controller controller = findControllerByname(sname);
//            Method doGet = aClass.getMethod("doGet", HttpServletRequest.class, HttpServletResponse.class);
//            doGet.invoke(o,req,resp);
            controller.doGet(req,resp);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       this.doGet(req,resp);
    }
}
